package com.devbobcorn.nekorization.entities.goal;

import com.devbobcorn.nekorization.entities.NekoEntity;
import com.devbobcorn.nekorization.entities.SpriteEntity;

import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.ai.goal.Goal;
import net.minecraft.world.phys.AABB;

public class LandOnNekoHeadGoal extends Goal {
    private final SpriteEntity entity;
    private NekoEntity target;
    private boolean isSittingOnHead;

    public LandOnNekoHeadGoal(SpriteEntity entity) {
        this.entity = entity;
    }

    private static final int WIDTH  = 3;
    private static final int HEIGHT = 3;

    public boolean canUse() {
        NekoEntity targetEntity = null;
        double minDistSqr = Double.MAX_VALUE;
        for (Entity neko : entity.level.getEntities(entity,
            new AABB(entity.xo - WIDTH, entity.yo - HEIGHT, entity.zo - WIDTH, entity.xo + WIDTH, entity.yo + HEIGHT, entity.zo + WIDTH),
            (en) -> { return en instanceof NekoEntity; })) {
                if (neko.distanceToSqr(this.entity) < minDistSqr) {
                    targetEntity = (NekoEntity) neko;
                    minDistSqr = targetEntity.distanceToSqr(this.entity);
                }
            }
        if (targetEntity == null)
            return false;
        boolean flag = targetEntity != null && !targetEntity.isSpectator() && !targetEntity.isInWater() && !targetEntity.isInPowderSnow;
        return !this.entity.isOrderedToSit() && flag && this.entity.canSitOnShoulder();
    }

    public boolean isInterruptable() {
        return !this.isSittingOnHead;
    }

    public void start() {
        this.target = null;
        double minDistSqr = Double.MAX_VALUE;
        for (Entity neko : entity.level.getEntities(entity,
            new AABB(entity.xo - WIDTH, entity.yo - HEIGHT, entity.zo - WIDTH, entity.xo + WIDTH, entity.yo + HEIGHT, entity.zo + WIDTH),
            (en) -> { return en instanceof NekoEntity; })) {
                if (neko.distanceToSqr(this.entity) < minDistSqr) {
                    this.target = (NekoEntity) neko;
                    minDistSqr = this.target.distanceToSqr(this.entity);
                }
            }
        this.isSittingOnHead = false;
    }

    public void tick() {
        if (!this.isSittingOnHead && !this.entity.isInSittingPose() && !this.entity.isLeashed()) {
            if (this.entity.getBoundingBox().inflate(2.0).intersects(this.target.getBoundingBox())) {
                this.isSittingOnHead = this.entity.setEntityOnHead(this.target);
            }
        }
    }
}